import { defineStore } from 'pinia'
import arrayToTree from 'array-to-tree'
import {
  deletePageById,
  postPageListData,
  createPageData,
  updatePageById
} from '@/api/main/system/system'

type ISystemState = {
  pageList: any[]
  pageTotalCount: number
}

/**
 * @description: 系统模块的仓库
 */
const useSystemStore = defineStore('system', {
  state: (): ISystemState => ({
    pageList: [],
    pageTotalCount: 0
  }),
  actions: {
    /**
     * 系统模块的仓库获取全部数据行为
     * @param pageName 页面名称
     * @param queryInfo 请求参数
     */
    async postListAction(pageName: string, queryInfo: any) {
      const usersListResult = await postPageListData(pageName, queryInfo)
      if (!usersListResult || !usersListResult.data) return

      const { list, total } = usersListResult.data
      if (pageName === 'system/menu') {
        const tree = arrayToTree(list, {
          customID: '_id',
          parentProperty: 'parentId',
          childrenProperty: 'children'
        })
        this.pageList = tree
      } else {
        this.pageList = list
      }
      this.pageTotalCount = total
    },

    async deletePageByIdAction(pageName: string, id: string) {
      await deletePageById(pageName, id)
      this.postListAction(pageName, { limit: 10, page: 1 })
    },

    async createPageAction(pageName: string, newData: any) {
      await createPageData(pageName, newData)
      this.postListAction(pageName, { limit: 10, page: 1 })
    },

    async updatePageAction(pageName: string, id: string, newData: any) {
      await updatePageById(pageName, id, newData)
      this.postListAction(pageName, { limit: 10, page: 1 })
    }
  }
})

export default useSystemStore
